#region license
# This file is part of Grawlix.
# 
# Grawlix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
# 
# Grawlix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with Grawlix.  If not, see
# <http://www.gnu.org/licenses/>.
#endregion

"""Default scheme for multiple-instance creation of Domains."""

namespace Grawlix.Services
import C5
import System

final transient class SingleAssemblyDomainFactory(ServiceBase, IDomainFactory):
"""
Creates and caches Domains, using
the same assembly for each domain.
"""
	
	def constructor(
		[required] environmentFactory as IEnvironmentFactory,
		[required] assembly as string,
		[required] constraints as Type*):
	"""
	Create a domain factory that injects
	domains into the current AppDomain.
	Param environmentFactory: A factory service to create new
		environments for the created domains.
	Param assembly: The assembly to load governor instances from.
	Param constraints: Interfaces that domain governors must implement.
	"""
		_environmentFactory = environmentFactory
		_assembly = assembly
		for constraint in constraints:
			if not constraint.IsInterface:
				raise ArgumentException(
					"Unable to create a <Domain> with " +
					"non-interface constraints.",
					"constraints")
			_constraints.Add(constraint)
	
	def Create([required] name as string, [required] game as Game):
	"""
	Look up a domain by name, loading if needed.
	Param game: The game to create the domain in.
	Param name: The name of the domain to access.
	Returns: A proxy to the domain, which is not yet activated.
	"""
		environment = _environmentFactory.Create(name)
		domain = ExternalProxy[of Domain](
			environment,
			Domain,
			name, _assembly, game, Constraints)
		return domain
	
	override def ToString():
	"""
	Get a string representation for this object.
	Returns: A string representation for this object.
	"""
		return "SingleAssemblyDomainFactory ${_assembly}"
	
	private _environmentFactory as IEnvironmentFactory
	"""Whether to create a new appdomain environment."""
	
	private _assembly as string
	"""The assembly to load from."""
	
	Constraints as IList[of Type]:
	"""The interfaces a controller must implement."""
		get:
			return GuardedList[of Type](_constraints)
	
	private _constraints = ArrayList[of Type]()
	"""The type of domain environment to spawn."""
	
